package com.wetao.module_user.activity;

import android.content.Intent;
import android.os.Build;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;


import com.wetao.lib_common.ConstantArouter;
import com.wetao.lib_common.Constants;
import com.wetao.lib_common.EventBus.EventBusMessage;
import com.wetao.lib_common.base.BaseActivity;
import com.wetao.lib_common.base.BaseListResponse;
import com.wetao.lib_common.base.BaseResponse;
import com.wetao.lib_common.bean.response.AppVersionInfo;
import com.wetao.lib_common.bean.response.AreaSchoolInfo;
import com.wetao.lib_common.bean.response.Loginbean;
import com.wetao.lib_common.bean.response.Loginbean_CoachClass;
import com.wetao.lib_common.bean.response.SchoolClassInfo;
import com.wetao.lib_common.bean.response.SchoolGradeInfo;
import com.wetao.lib_common.greendao.DBUtils;
import com.wetao.lib_common.net.cookies.CookiesManager;
import com.wetao.lib_common.tsdBlePen.TsdService;
import com.wetao.lib_common.utils.ComUtil;
import com.wetao.lib_common.utils.ConstantUtils;
import com.wetao.lib_common.utils.JsonUtils;
import com.wetao.lib_common.utils.LogUtils;
import com.wetao.lib_common.utils.SPUtils;
import com.wetao.lib_common.utils.ToastUtil;
import com.wetao.lib_common.view.OnMultiClickListener;
import com.wetao.lib_common.view.verticaltablayout.VerticalTabLayout;
import com.wetao.lib_common.view.verticaltablayout.adapter.TabAdapter;
import com.wetao.lib_common.view.verticaltablayout.widget.ITabView;
import com.wetao.lib_common.view.verticaltablayout.widget.QTabView;
import com.wetao.module_user.R;
import com.wetao.module_user.contract.UserActivityContract;
import com.wetao.lib_common.view.dialog.CustomDialog;
import com.wetao.module_user.dialog.DialogSwitchSchool;
import com.wetao.lib_common.view.dialog.OnCustomDialogItemClickListener;
import com.wetao.module_user.fragment.UserClassAdminFragment;
import com.wetao.module_user.fragment.UserClassTeachFragment;
import com.wetao.module_user.fragment.UserInfoFragment;
import com.wetao.module_user.fragment.UserPenFragment;
import com.wetao.module_user.fragment.UserSettingFragment;
import com.wetao.module_user.fragment.UserUpgradeFragment;
import com.wetao.module_user.presenter.UserActivityPresenter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.forward.androids.utils.Util;

/**
 * 所有模块统一登录页面
 */
@Route(path = ConstantArouter.PATH_USER_USERACTIVITY)
public class UserActivity extends BaseActivity<UserActivityContract.View, UserActivityContract.Presenter> implements
        UserActivityContract.View {
    private ImageView ivUserBack;
    private ImageView ivHead;
    private TextView tvName;
    private ViewPager vpContent;
    private VerticalTabLayout verticalTab;

    private Loginbean loginbean;
    private UserInfoFragment userInfoFragment;
    private UserClassAdminFragment userClassAdminFragment;
    private UserClassTeachFragment userClassTeachFragment;
    private UserSettingFragment userSettingFragment;
    private UserUpgradeFragment userUpgradeFragment;

    private FragmentManager fragmentManager;//声明fragment管理
    private final List<Fragment> fragmentList = new ArrayList<>();

    private String[] mTitles = {"个人资料", "我的行政班级", "我的选课班级", "我的智能笔", "版本更新", "设置"};
    private int[] mIconNormals = {R.drawable.user_ic_person, R.drawable.user_ic_admin, R.drawable.user_ic_teach,
            R.drawable.user_ic_pen, R.drawable.user_ic_upgrade, R.drawable.user_ic_setting};
    private int[] mIconSelects = {R.drawable.user_ic_person_p, R.drawable.user_ic_admin_p, R.drawable.user_ic_teach_p,
            R.drawable.user_ic_pen_p, R.drawable.user_ic_upgrade_p, R.drawable.user_ic_setting_p};



    private final int DIALOG_CLASS_COACH_EXIT = 3;
    private final int DIALOG_USER_COACH_EXIT = 4;

    @Override
    public int getLayoutId() {
        return R.layout.user_activity_main;
    }

    @Override
    public boolean getIsBindTsdService() {
        return false;
    }

    @Override
    public TsdService.OnDataReceiveListener getTsdServiceDataReceiveListener() {
        return null;
    }


    @Override
    public UserActivityContract.Presenter createPresenter() {
        return new UserActivityPresenter(this);
    }

    @Override
    public UserActivityContract.View createView() {
        return this;
    }

    @Override
    public void init() {
        //加上头部布局会造成视图显示不全
//        hideBottomUIMenu();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        findViewById();

        String userBean = SPUtils.getInstance().getString(Constants.USER_LOGIN_INFO);
        if (userBean != null && !TextUtils.isEmpty(userBean)) {
            loginbean = JsonUtils.fromJson(userBean, Loginbean.class);
            if (null != loginbean) {
                tvName.setText(loginbean.getName());
                if (!TextUtils.isEmpty(loginbean.getAvatarUrl())) {
                    Glide.with(this)
                            .load(loginbean.getAvatarUrl())
                            .error(R.drawable.user_ic_head_default)
                            .into(ivHead);
                }

                initInfoFragment();

                initClassAdminFrament();

                initClassTeachFragment();

                initSettingFrament();

                initUpgradeFragment();

                initFragmentList();
            }
        } else {
            finish();
            return;
        }
    }

    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {

            Window _window = getWindow();
            WindowManager.LayoutParams params = _window.getAttributes();
            params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE;
            _window.setAttributes(params);
        }
    }

    private void initFragmentList() {
        fragmentList.add(userInfoFragment);
        fragmentList.add(userClassAdminFragment);
        fragmentList.add(userClassTeachFragment);
        fragmentList.add(UserPenFragment.newInstance(SPUtils.getInstance().getString(Constants.USER_PEN_MAC)));
        fragmentList.add(userUpgradeFragment);
        fragmentList.add(userSettingFragment);
        fragmentManager = getSupportFragmentManager();
        vpContent.setAdapter(new ViewPagerAdapter(getSupportFragmentManager(), fragmentList));

        verticalTab.setupWithViewPager(vpContent);
        verticalTab.setTabAdapter(new TabAdapter() {
            @Override
            public int getCount() {
                return mTitles.length;
            }

            @Override
            public ITabView.TabBadge getBadge(int position) {
                return null;
            }

            @Override
            public ITabView.TabIcon getIcon(int position) {
                QTabView.TabIcon icon = new QTabView.TabIcon.Builder()
                        .setIcon(mIconSelects[position], mIconNormals[position])//设置数据   也有设置字体颜色的方法
                        .setIconGravity(Gravity.START)
                        .setArrowVisual(true)
                        .setIconMargin(Util.dp2px(UserActivity.this, 6))
                        .setIconSize(Util.dp2px(UserActivity.this, 24), Util.dp2px(UserActivity.this, 24))
                        .build();
                return icon;
            }

            @Override
            public ITabView.TabTitle getTitle(int position) {
                QTabView.TabTitle title = new QTabView.TabTitle.Builder()
                        .setContent(mTitles[position])//设置数据   也有设置字体颜色的方法
                        .setTextSize((int)getResources().getDimension(R.dimen.dp_12))
                        .setOrientation(LinearLayout.HORIZONTAL)
                        .setTextColor(getResources().getColor(R.color.user_tab_select_color), getResources().getColor(R.color.user_tab_normal_color))
                        .build();
                return title;
            }

            @Override
            public int getBackground(int position) {
                return -1;
            }
        });
    }

    private void initClassTeachFragment() {
        if(null == userClassTeachFragment) {
            userClassTeachFragment = UserClassTeachFragment
                    .newInstance(JsonUtils.toJson(loginbean.getCoachClassResponseVos()));
            userClassTeachFragment.setOnListenClick(new UserClassTeachFragment.OnListenClick() {
                @Override
                public void onListenClick() {
                    showSwitchAddClassDialog(getResources().getString(R.string.user_class_coach_add),
                            "", null, "",null,"", null, DialogSwitchSchool.DIALOG_CLASS_COACH_JOIN);
                }

                @Override
                public void onItemClickSwitch(Loginbean_CoachClass coachClass) {
                    StringBuilder sb = new StringBuilder();
                    sb.append(coachClass.getProvince()).append("/");
                    sb.append(coachClass.getCity()).append("/");
                    sb.append(coachClass.getDistrict()).append("/");
                    sb.append(coachClass.getSchoolName());
                    showSwitchAddClassDialog(getResources().getString(R.string.user_class_coach_update),
                            sb.toString(), coachClass.getSchoolId(),
                            coachClass.getGradeName(), coachClass.getGradeId(),
                            coachClass.getClassName(), coachClass.getId(), DialogSwitchSchool.DIALOG_CLASS_COACH_UPDATE);
                }

                @Override
                public void onItemClickExit(Loginbean_CoachClass coachClass) {
                    showExitDialog(coachClass.getId(), getResources().getString(R.string.user_exit_class_title), getResources().getString(R.string.user_exit_class), DIALOG_CLASS_COACH_EXIT);
                }
            });
        }
    }

    private void initClassAdminFrament() {
        if(null == userClassAdminFragment) {
            userClassAdminFragment = UserClassAdminFragment
                    .newInstance(new StringBuilder(loginbean.getSchoolName()).append("/")
                            .append(TextUtils.isEmpty(loginbean.getClassName()) ? "": loginbean.getClassName()).toString(), loginbean.getClassId());
            userClassAdminFragment.setOnListenClick(new UserClassAdminFragment.OnListenClick() {
                @Override
                public void onListenClick() {
                    StringBuilder sb = new StringBuilder();
                    sb.append(loginbean.getProvince()).append("/");
                    sb.append(loginbean.getCity()).append("/");
                    sb.append(loginbean.getDistrict()).append("/");
                    sb.append(loginbean.getSchoolName());
                    showSwitchAddClassDialog(getResources().getString(R.string.user_class_admin_update), sb.toString(), loginbean.getSchoolId(),
                            loginbean.getGrade(), loginbean.getItemGrade(), loginbean.getClassName(), loginbean.getClassId(), DialogSwitchSchool.DIALOG_CLASS_ADMIN_UPDATE);
                }
            });
        }
    }

    private void initInfoFragment() {
        if(null == userInfoFragment) {
            userInfoFragment = UserInfoFragment
                    .newInstance(loginbean.getAccount(), loginbean.getName(), loginbean.getMobile());
            userInfoFragment.setOnListenClick(new UserInfoFragment.OnListenClick() {
                @Override
                public void onListenClick() {
                    showUpdatePhoneDialog();
                }
            });
        }
    }

    private void initSettingFrament() {
        if(null == userSettingFragment) {
            userSettingFragment = UserSettingFragment
                    .newInstance();
            userSettingFragment.setOnListenClick(new UserSettingFragment.OnListenClick() {
                @Override
                public void onListenPwdClick() {
                    showUpdatePwdDialog();
                }

                @Override
                public void onListenExitClick() {
                    showExitDialog(0, getResources().getString(R.string.user_loginout_title), getResources().getString(R.string.user_loginout_tip), DIALOG_USER_COACH_EXIT);
                }
            });
        }
    }


    private void initUpgradeFragment() {
        if(null == userUpgradeFragment) {
            userUpgradeFragment = UserUpgradeFragment
                    .newInstance();
            userUpgradeFragment.setOnListenClick(new UserUpgradeFragment.OnListenClick() {
                @Override
                public void onListenUpgradeClick() {
                    //showUpdatePhoneDialog();
                    getPresenter().getClientVersionInfo((HashMap<String, Object>) ComUtil.getHashmapByStr(
                            new String[]{"version"},
                            new Object[]{ConstantUtils.getAppVersionName()}), false, true);
                }
            });
        }
    }


    private void findViewById() {
        ivUserBack = findViewById(R.id.iv_user_back);
        ivUserBack.setOnClickListener(new OnMultiClickListener() {
            @Override
            public void onMultiClick(View v) {
                finish();
            }
        });
        ivHead = findViewById(R.id.iv_head);
        tvName = findViewById(R.id.tv_name);
        vpContent = findViewById(R.id.vp_content);
        verticalTab = findViewById(R.id.vertical_tab);
    }

    private class ViewPagerAdapter extends FragmentPagerAdapter {
        private List<Fragment> list;

        public ViewPagerAdapter(FragmentManager fm, List<Fragment> list) {
            super(fm);
            this.list = list;
        }

        @Override
        public Fragment getItem(int position) {
            return list.get(position);
        }

        @Override
        public int getCount() {
            return list.size();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    public void getAreaInfoResult(BaseListResponse<AreaSchoolInfo> data) {
        if(null == data) return;
        LogUtils.i("getAreaInfoResult data " + data.toString());

        final List<AreaSchoolInfo> areaSchoolInfos=data.getData();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(null != mDialogSwitchSchool) {
                    mDialogSwitchSchool.displaySchool(areaSchoolInfos);
                }
            }
        });
    }


    private volatile int areaType = 1;
    private StringBuilder schoolAllName = new StringBuilder();
    interface OnListenFlexLayout{
        void onListenFlexLayout(Object info);
    }



    @Override
    public void getAreaInfoError() {
    }

    @Override
    public void getCheckCodeResult(BaseResponse data) {

    }

    @Override
    public void getCheckCodeError() {

    }

    @Override
    public void getModifyPhoneResult(BaseResponse<Loginbean> data) {
        if(null == data) return;
        LogUtils.i("getModifyPhoneResult data " + data.toString());
        loginbean = data.getData();
        SPUtils.getInstance().put(Constants.USER_LOGIN_INFO,JsonUtils.toJson(loginbean));

        String loginAccountPwd = SPUtils.getInstance().getString(Constants.USER_ID_LIST,"");
        boolean isRemmeber = SPUtils.getInstance().getBoolean(Constants.IS_REMMBER_PASSWORD, false);
        if (!TextUtils.isEmpty(loginAccountPwd)){
            StringBuilder sb = new StringBuilder(loginbean.getAccount());
            if(isRemmeber) {
                sb.append("/");
                sb.append(loginAccountPwd.split("/")[1]);
            }
            SPUtils.getInstance().put(Constants.USER_ID_LIST, sb.toString());
        }

        EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_UPDATE_PHONE, loginbean.getMobile() + "###" + loginbean.getAccount()));

        deleteDialogUpdatePhone();

        ToastUtil.initToast("更新手机号成功!");
    }

    @Override
    public void getModifyPhoneError() {

    }

    @Override
    public void getModifyPwdResult(BaseResponse data) {
        if(null != mCustomDialogUpdatePwd) {
            mCustomDialogUpdatePwd.dismiss();
            mCustomDialogUpdatePwd = null;
        }

        ToastUtil.initToast("更新密码成功!");

        EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_OUTLOGIN, null));

        DBUtils.getInstance(this).close();
        DBUtils.getInstance(this).clear();


        //清除所有Cookies缓存内容
        CookiesManager.clearAllCookies();
        SPUtils.getInstance().put(Constants.HEAD_XTOKEN, "");
        SPUtils.getInstance().put(Constants.USER_ID_KEY, "");

        ARouter.getInstance().build(ConstantArouter.PATH_COMMON_LOGINACTIVITY)
                .withFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
                        |Intent.FLAG_ACTIVITY_NEW_TASK)
                .navigation();
    }

    @Override
    public void getModifyPwdError() {

    }


    @Override
    public void getSectionGradeResult(BaseListResponse<SchoolGradeInfo> data) {
        if(null == data) return;
        LogUtils.i("getSectionGradeResult data " + data.toString());
        final List<SchoolGradeInfo> schoolGradeInfoList = data.getData();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(null != mDialogSwitchSchool) {
                    mDialogSwitchSchool.displayGrade(schoolGradeInfoList);
                }
            }
        });
    }



    @Override
    public void getSectionGradeError() {

    }

    @Override
    public void getClassAdminUpdateResult(BaseResponse<Loginbean> data) {
        if(null == data) return;
        loginbean = data.getData();
        SPUtils.getInstance().put(Constants.USER_LOGIN_INFO,JsonUtils.toJson(loginbean));

        EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_UPDATE_CLASS_ADMIN,
                new StringBuilder(loginbean.getSchoolName()).append("/")
                        .append(TextUtils.isEmpty(loginbean.getClassName()) ? "": loginbean.getClassName())
                        .toString()));
        if(null != mDialogSwitchSchool) {
            mDialogSwitchSchool.deleteDialogSwitchAddClass();
        }

        ToastUtil.initToast("更换行政班成功!");
    }

    @Override
    public void getClassAdminUpdatError() {

    }

    @Override
    public void getClassCoachJoinResult(BaseListResponse<Loginbean_CoachClass> data) {
        if(null == data) return;
        loginbean.setCoachClassResponseVos(data.getData());
        SPUtils.getInstance().put(Constants.USER_LOGIN_INFO,JsonUtils.toJson(loginbean));

        EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_UPDATE_JOIN_EXIT_CLASS_COACH, JsonUtils.toJson(loginbean.getCoachClassResponseVos())));
        if(null != mDialogSwitchSchool) {
            mDialogSwitchSchool.deleteDialogSwitchAddClass();
        }

        ToastUtil.initToast("加入新选课班成功!");
    }

    @Override
    public void getClassCoachJoinError() {

    }

    @Override
    public void getClassCoachUpdateResult(BaseListResponse<Loginbean_CoachClass> data) {
        if(null == data) return;
        loginbean.setCoachClassResponseVos(data.getData());
        SPUtils.getInstance().put(Constants.USER_LOGIN_INFO,JsonUtils.toJson(loginbean));

        EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_UPDATE_JOIN_EXIT_CLASS_COACH, JsonUtils.toJson(loginbean.getCoachClassResponseVos())));
        if(null != mDialogSwitchSchool) {
            mDialogSwitchSchool.deleteDialogSwitchAddClass();
        }

        ToastUtil.initToast("更新选课班成功!");
    }

    @Override
    public void getClassCoachUpdateError() {

    }

    @Override
    public void getClassCoachExitResult(BaseListResponse<Loginbean_CoachClass> data) {
        if(null == data) return;
        loginbean.setCoachClassResponseVos(data.getData());
        SPUtils.getInstance().put(Constants.USER_LOGIN_INFO,JsonUtils.toJson(loginbean));

        EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_UPDATE_JOIN_EXIT_CLASS_COACH, JsonUtils.toJson(loginbean.getCoachClassResponseVos())));
        //deleteDialogSwitchAddClass();
        mCustomDialogExitClass.dismiss();

        ToastUtil.initToast("退出选课班成功!");
    }

    @Override
    public void getClassCoachExitError() {

    }

    @Override
    public void getChoiceClassResult(BaseListResponse<SchoolClassInfo> data) {
        if(null == data) return;
        LogUtils.i("getChoiceClassResult data " + data.toString());
        final List<SchoolClassInfo> schoolClassInfoList = data.getData();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(null != mDialogSwitchSchool) {
                    mDialogSwitchSchool.displayClass(schoolClassInfoList);
                }
            }
        });
    }

    @Override
    public void getChoiceClassError() {

    }

    @Override
    public void getAdminClassListResult(BaseListResponse<SchoolClassInfo> data) {
        if(null == data) return;
        LogUtils.i("getAdminClassListResult data " + data.toString());
        final List<SchoolClassInfo> schoolClassAdminInfoList = data.getData();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(null != mDialogSwitchSchool) {
                    mDialogSwitchSchool.displayAdminClass(schoolClassAdminInfoList);
                }
            }
        });
    }

    @Override
    public void getAdminClassListError() {

    }

    @Override
    public void getClientVersionResult(BaseResponse<AppVersionInfo> data) {
        if(null == data) return;
        LogUtils.i("getClientVersionResult data " + data.toString());
        AppVersionInfo appVersionInfo = data.getData();
        /*if(null == appVersionInfo) {
            appVersionInfo = new AppVersionInfo();
            appVersionInfo.setDownloadUrl("http://alioss-xxy.xiangxue.xin/202106/16244118817559709.apk");
            appVersionInfo.setDescription("1.修复考试试卷批改后分值显示不正常\n 2.新增断网后重新连接机制\n 3.优化版本记录显示\n 4.优化辅导资料模块教学视频打开逻辑\n 5.修复考试过程中重启，丢失学生作答数据问题\n 6.修复若干bug");
            appVersionInfo.setVersion("1.0.1");
            appVersionInfo.setApkSize(1024);
        }*/
        if(null != appVersionInfo) {
            if(!TextUtils.isEmpty(appVersionInfo.getDownloadUrl())) {
                showUpgradeDialog(appVersionInfo.getVersion(), ComUtil.getApkSize(appVersionInfo.getApkSize()),
                        appVersionInfo.getDescription(), appVersionInfo);
            } else {
                ToastUtil.initToast("当前已是最新版本");
            }
        }else {
            ToastUtil.initToast("当前已是最新版本");
        }
    }

    @Override
    public void getClientVersionError() {

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        if(null != mTimeCount) {
            mTimeCount.cancel();
            mTimeCount = null;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void busGetMessage(EventBusMessage messageEvent) {
        //LogUtils.i("m1: bus" + messageEvent.toString());
    }


    void deleteDialogUpdatePhone(){
        mCustomDialogUpdatePhone.dismiss();
        mCustomDialogUpdatePhone = null;
    }
    CustomDialog mCustomDialogUpdatePhone;
    private void showUpdatePhoneDialog() {
        //if(null == mCustomDialogUpdatePhone)
        {
            mCustomDialogUpdatePhone = new CustomDialog(this,
                    R.layout.user_dialog_phone_update,
                    new int[]{R.id.ib_delete, R.id.tv_get_code, R.id.bt_cancel, R.id.bt_ok, R.id.iv_eye},
                    0,
                    false,
                    true,
                    Gravity.CENTER);
            mCustomDialogUpdatePhone.setOnDialogItemClickListener(new OnCustomDialogItemClickListener() {
                @Override
                public void OnCustomDialogItemClick(CustomDialog dialog, View view) {
                    int id = view.getId();
                    if (id == R.id.ib_delete) {
                        deleteDialogUpdatePhone();
                    } else if (id == R.id.tv_get_code) {
                        AppCompatEditText etPhone = mCustomDialogUpdatePhone.findViewById(R.id.et_input_phone);
                        if (!TextUtils.isEmpty(etPhone.getText().toString())
                                && checkTel(etPhone.getText().toString().trim())) {
                            if (null == mTimeCount) {
                                mTimeCount = new TimeCount(60000, 1000);
                                mTimeCount.setTextView((AppCompatTextView) view);
                            }
                            mTimeCount.start();

                            getPresenter().getCheckCodeInfo((HashMap<String, Object>) ComUtil.getHashmapByStr(
                                    new String[]{"mobile", "type"}, new Object[]{etPhone.getText().toString(), 12}), false, true);
                        } else {
                            ToastUtil.initToast("请输入正确手机号码!");
                        }
                    } else if (id == R.id.bt_cancel) {
                        deleteDialogUpdatePhone();
                    } else if (id == R.id.bt_ok) {
                        AppCompatEditText etPhone = mCustomDialogUpdatePhone.findViewById(R.id.et_input_phone);
                        if (!TextUtils.isEmpty(etPhone.getText().toString())
                                && checkTel(etPhone.getText().toString().trim())) {
                            AppCompatEditText etInputPwd = mCustomDialogUpdatePhone.findViewById(R.id.et_input_pwd);
                            if (TextUtils.isEmpty(etInputPwd.getText().toString())) {
                                ToastUtil.initToast("请输入密码!");
                                return;
                            }
                            AppCompatEditText etCheckNum = mCustomDialogUpdatePhone.findViewById(R.id.et_input_check_num);
                            if (!TextUtils.isEmpty(etCheckNum.getText().toString())) {
                                getPresenter().getModifyPhoneInfo((HashMap<String, Object>) ComUtil.getHashmapByStr(
                                        new String[]{"mobile", "password", "verifyCode"},
                                        new Object[]{etPhone.getText().toString(), etInputPwd.getText().toString(), etCheckNum.getText().toString()}), false, false);
                            } else {
                                ToastUtil.initToast("请输入验证码!");
                            }
                        } else {
                            ToastUtil.initToast("请输入正确手机号码!");
                        }
                    } else if (id == R.id.iv_eye) {
                        AppCompatEditText etPwd = (AppCompatEditText) dialog.findViewById(R.id.et_input_pwd);
                        if ("0".equals((String) view.getTag())) {
                            view.setTag("1");
                            ((AppCompatImageView) view).setImageResource(R.drawable.common_login_eye_open);
                            etPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                        } else {
                            view.setTag("0");
                            ((AppCompatImageView) view).setImageResource(R.drawable.common_login_eye_close);
                            etPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                        }
                    }
                }
            });
        }

        mCustomDialogUpdatePhone.show();

        AppCompatEditText etPhone = mCustomDialogUpdatePhone.findViewById(R.id.et_input_phone);
        etPhone.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        AppCompatEditText etCheckNum = mCustomDialogUpdatePhone.findViewById(R.id.et_input_check_num);
        etCheckNum.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
    }

    public boolean checkTel(String tel){
        Pattern p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$");
        Matcher matcher = p.matcher(tel);
        return matcher.matches();
    }


    private TimeCount mTimeCount;
    class TimeCount extends CountDownTimer {
        private AppCompatTextView textView;

        public void setTextView(AppCompatTextView textView) {
            this.textView = textView;
        }

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long l) {
            textView.setClickable(false);
            textView.setText(l/1000 + "秒后重新获取");
        }

        @Override
        public void onFinish() {
            textView.setClickable(true);
            textView.setText("获取验证码");
        }
    }

    private CustomDialog mCustomDialogUpdatePwd;
    private void showUpdatePwdDialog() {
        //if(null == mCustomDialogUpdatePwd)
        {
            mCustomDialogUpdatePwd = new CustomDialog(this,
                    R.layout.user_dialog_pwd_update,
                    new int[]{R.id.ib_delete, R.id.bt_cancel, R.id.bt_ok, R.id.iv_eye, R.id.iv_re_eye,R.id.iv_check_eye,
                              R.id.et_reinput_pwd, R.id.et_input_new_pwd},
                    0,
                    false,
                    true,
                    Gravity.CENTER);
            mCustomDialogUpdatePwd.setOnDialogItemClickListener(new OnCustomDialogItemClickListener() {
                @Override
                public void OnCustomDialogItemClick(CustomDialog dialog, View view) {
                    int id = view.getId();
                    if (id == R.id.ib_delete) {
                        mCustomDialogUpdatePwd.dismiss();
                    } else if (id == R.id.bt_cancel) {
                        mCustomDialogUpdatePwd.dismiss();
                    } else if (id == R.id.bt_ok) {
                        AppCompatEditText etPwd = (AppCompatEditText) dialog.findViewById(R.id.et_input_pwd);
                        AppCompatEditText etPwd2 = (AppCompatEditText) dialog.findViewById(R.id.et_reinput_pwd);
                        AppCompatEditText etPwdNew = (AppCompatEditText) dialog.findViewById(R.id.et_input_new_pwd);
                        if (!TextUtils.isEmpty(etPwd.getText().toString())) {
                            if (!TextUtils.isEmpty(etPwd2.getText().toString())){
                                if (!etPwd2.getText().toString().equals(etPwd.getText().toString())){
                                    if (!TextUtils.isEmpty(etPwdNew.getText().toString())){
                                        if (etPwd2.getText().toString().equals(etPwdNew.getText().toString())){
                                            String newPwd = etPwdNew.getText().toString();
                                            if(newPwd.length() < 6){
                                                ToastUtil.initToast("请输入至少6位的新密码");
                                                return;
                                            }
                                            char[] temC = newPwd.toCharArray();

                                            boolean isChar = false, isNum = false;
                                            for (int i = 0; i < temC.length; i++) {
                                                if (temC[i] >= 65 && temC[i] <= 90) {//大写字母
                                                    isChar = true;
                                                    break;
                                                }
                                                if (temC[i] >= 97 && temC[i] <= 122) {//小写字母
                                                    isChar = true;
                                                    break;
                                                }
                                            }
                                            for (int i = 0; i < temC.length; i++) {
                                                if (temC[i] >= 48 && temC[i] <= 57) {//数字
                                                    isNum = true;
                                                    break;
                                                }
                                            }
                                            if(isChar && isNum) {
                                                getPresenter().getModifyPwdInfo((HashMap<String, Object>) ComUtil.getHashmapByStr(
                                                        new String[]{"newPassword", "oldPassword"},
                                                        new Object[]{etPwdNew.getText().toString(), etPwd.getText().toString()}), false, false);
                                            } else {
                                                ToastUtil.initToast("请输入含数字/字母2种组合的新密码");
                                            }
                                        }else {
                                            ToastUtil.initToast("请输入相同的新密码");
                                        }
                                    }else {
                                        ToastUtil.initToast("请再次输入新密码");
                                    }
                                }else{
                                    ToastUtil.initToast("新密码不能与旧密码相同");
                                }
                            }else{
                                ToastUtil.initToast("请输入新密码");
                            }
                        } else {
                            ToastUtil.initToast("请输入原始密码");
                        }
                    } else if (id == R.id.iv_eye) {
                        AppCompatEditText etPwd = (AppCompatEditText) dialog.findViewById(R.id.et_input_pwd);
                        if ("0".equals((String) view.getTag())) {
                            view.setTag("1");
                            ((AppCompatImageView) view).setImageResource(R.drawable.common_login_eye_open);
                            etPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                        } else {
                            view.setTag("0");
                            ((AppCompatImageView) view).setImageResource(R.drawable.common_login_eye_close);
                            etPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                        }
                    } else if (id == R.id.iv_re_eye) {
                        AppCompatEditText etPwd = (AppCompatEditText) dialog.findViewById(R.id.et_reinput_pwd);
                        if ("0".equals((String) view.getTag())) {
                            view.setTag("1");
                            ((AppCompatImageView) view).setImageResource(R.drawable.common_login_eye_open);
                            etPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                        } else {
                            view.setTag("0");
                            ((AppCompatImageView) view).setImageResource(R.drawable.common_login_eye_close);
                            etPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                        }
                    }else if (id == R.id.iv_check_eye){
                        AppCompatEditText etPwd = (AppCompatEditText) dialog.findViewById(R.id.et_input_new_pwd);
                        if ("0".equals((String) view.getTag())) {
                            view.setTag("1");
                            ((AppCompatImageView) view).setImageResource(R.drawable.common_login_eye_open);
                            etPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                        } else {
                            view.setTag("0");
                            ((AppCompatImageView) view).setImageResource(R.drawable.common_login_eye_close);
                            etPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                        }
                    }
                }
            });
        }

        mCustomDialogUpdatePwd.show();

        final List<View> viewList = mCustomDialogUpdatePwd.getViews();
        if(null != viewList) {
            if(null != viewList.get(6)) {
                ((AppCompatEditText)viewList.get(6)).addTextChangedListener(new TextWatcher() {

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {


                    }


                    @Override
                    public void afterTextChanged(Editable edt) {
                        try {
                            String temp = edt.toString();
                            String tem = temp.substring(temp.length() - 1, temp.length());
                            char[] temC = tem.toCharArray();
                            int mid = temC[0];
                            if (mid >= 48 && mid <= 57) {//数字
                                return;
                            }
                            if (mid >= 65 && mid <= 90) {//大写字母
                                return;
                            }
                            if (mid >= 97 && mid <= 122) {//小写字母
                                return;
                            }
                            edt.delete(temp.length() - 1, temp.length());
                        } catch (Exception e) {
                            //throw new Exception("登录页面监听密码输入框只能输入数字或者英文出错");
                            // TODO: handle exception
                        }
                    }

                });
            }
            if(null != viewList.get(7)) {
                ((AppCompatEditText)viewList.get(7)).addTextChangedListener(new TextWatcher() {

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {


                    }


                    @Override
                    public void afterTextChanged(Editable edt) {
                        try {
                            String temp = edt.toString();
                            String tem = temp.substring(temp.length() - 1, temp.length());
                            char[] temC = tem.toCharArray();
                            int mid = temC[0];
                            if (mid >= 48 && mid <= 57) {//数字
                                return;
                            }
                            if (mid >= 65 && mid <= 90) {//大写字母
                                return;
                            }
                            if (mid >= 97 && mid <= 122) {//小写字母
                                return;
                            }
                            edt.delete(temp.length() - 1, temp.length());
                        } catch (Exception e) {
                            //throw new Exception("登录页面监听密码输入框只能输入数字或者英文出错");
                            // TODO: handle exception
                        }
                    }

                });
            }
        }
    }


    private CustomDialog mCustomDialogExitClass;
    private void showExitDialog(Integer classId, String title, String tip, int type) {
        //if(null == mCustomDialogExitClass)
        {
            mCustomDialogExitClass = new CustomDialog(this,
                    R.layout.user_dialog_class_exit,
                    new int[]{R.id.ib_delete, R.id.bt_cancel, R.id.bt_ok, R.id.tv_titile, R.id.tv_exit_tip},
                    0,
                    false,
                    true,
                    Gravity.CENTER);
            mCustomDialogExitClass.setOnDialogItemClickListener(new OnCustomDialogItemClickListener() {
                @Override
                public void OnCustomDialogItemClick(CustomDialog dialog, View view) {
                    int id = view.getId();
                    if (id == R.id.ib_delete) {
                        mCustomDialogExitClass.dismiss();
                    } else if (id == R.id.bt_cancel) {
                        mCustomDialogExitClass.dismiss();
                    } else if (id == R.id.bt_ok) {
                        if(type == DIALOG_CLASS_COACH_EXIT) {
                            getPresenter().getClassCoachExitInfo((HashMap<String, Object>) ComUtil.getHashmapByStr(
                                    new String[]{"id"},
                                    new Object[]{classId}), true, false);
                        } else if(type == DIALOG_USER_COACH_EXIT) {
                            mCustomDialogExitClass.dismiss();

                            EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_OUTLOGIN, null));

                            DBUtils.getInstance(UserActivity.this).close();
                            DBUtils.getInstance(UserActivity.this).clear();


                            //清除所有Cookies缓存内容
                            CookiesManager.clearAllCookies();
                            SPUtils.getInstance().put(Constants.HEAD_XTOKEN, "");
                            SPUtils.getInstance().put(Constants.USER_ID_KEY, "");

                            ARouter.getInstance().build(ConstantArouter.PATH_COMMON_LOGINACTIVITY)
                                    .withFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
                                            |Intent.FLAG_ACTIVITY_NEW_TASK)
                                    .navigation();
                        }
                    }
                }
            });
        }

        mCustomDialogExitClass.show();

        final List<View> viewList = mCustomDialogExitClass.getViews();
        if(null != viewList) {
            if(!TextUtils.isEmpty(title)) {
                ((AppCompatTextView) viewList.get(3)).setText(title);
            }
            if(!TextUtils.isEmpty(tip)) {
                ((AppCompatTextView) viewList.get(4)).setText(tip);
            }
        }
    }


    DialogSwitchSchool mDialogSwitchSchool = null;
    private void showSwitchAddClassDialog(String title, String schoolName, Integer schoolId,
                                          String gradeName, Integer gradeId,
                                          String className, Integer classId, int type) {
        if(null == mDialogSwitchSchool){
            mDialogSwitchSchool = new DialogSwitchSchool(this, title, schoolName, schoolId, gradeName, gradeId, className, classId, type);
        } else {
            mDialogSwitchSchool.update(this, title, schoolName, schoolId, gradeName, gradeId, className, classId, type);
        }
        mDialogSwitchSchool.setOnListenDataReq(new DialogSwitchSchool.OnListenDataReq() {
            @Override
            public void onListenAreaReq(int areaType) {
                getPresenter().getAreaInfo((HashMap<String, Object>) ComUtil.getHashmapByStr(
                        new String[]{"areaType"}, new Object[]{areaType}), false, false);
            }

            @Override
            public void onListenAreaReq(int areaType, int id) {
                getPresenter().getAreaInfo((HashMap<String, Object>) ComUtil.getHashmapByStr(
                        new String[]{"areaType", "areaId"}, new Object[]{areaType, id}), false, false);
            }

            @Override
            public void onListenSchoolGradeReq(int schoolId) {
                getPresenter().getSectionGradeInfo((HashMap<String, Object>) ComUtil.getHashmapByStr(
                        new String[]{"schoolId"}, new Object[]{schoolId}), false, false);
            }

            @Override
            public void onListenGradeClassReq(int schoolId, int gradeId) {
                getPresenter().getChoiceClassInfo((HashMap<String, Object>) ComUtil.getHashmapByStr(
                        new String[]{"schoolId", "gradeId"}, new Object[]{schoolId, gradeId}), false, false);
            }

            @Override
            public void onListenGradeClassAdminReq(int schoolId, int gradeId) {
                getPresenter().getAdminClassListInfo((HashMap<String, Object>) ComUtil.getHashmapByStr(
                        new String[]{"schoolId", "itemGrade"}, new Object[]{schoolId, gradeId}), false, false);
            }

            @Override
            public void onListenClassCoachUpdateReq(int newId, int oldId) {
                getPresenter().getClassCoachUpdateInfo((HashMap<String, Object>) ComUtil.getHashmapByStr(
                        new String[]{"classId", "id"}, new Object[]{newId, oldId}), false, false);
            }

            @Override
            public void onListenClassCoachJoinReq(int id) {
                getPresenter().getClassCoachJoiInfo((HashMap<String, Object>) ComUtil.getHashmapByStr(
                        new String[]{"classId"}, new Object[]{id}), false, false);
            }

            @Override
            public void onListenClassAdminUpdateReq(int id) {
                getPresenter().getClassAdminUpdateInfo((HashMap<String, Object>) ComUtil.getHashmapByStr(
                        new String[]{"classId"}, new Object[]{id}), false, false);
            }
        });
        mDialogSwitchSchool.show();
    }



    private CustomDialog mCustomDialogUpgrade;
    private void showUpgradeDialog(String newVersion, String versionSize, String versionDes, AppVersionInfo versionInfo) {
       // if(null == mCustomDialogUpgrade)
        {
            mCustomDialogUpgrade = new CustomDialog(this,
                    R.layout.user_dialog_version_upgrade,
                    new int[]{R.id.ib_delete, R.id.bt_ok, R.id.tv_version_desc},
                    0,
                    false,
                    true,
                    Gravity.CENTER);
            mCustomDialogUpgrade.setOnDialogItemClickListener(new OnCustomDialogItemClickListener() {
                @Override
                public void OnCustomDialogItemClick(CustomDialog dialog, View view) {
                    int id = view.getId();
                    if (id == R.id.ib_delete) {
                        mCustomDialogUpgrade.dismiss();
                    } else if (id == R.id.bt_ok) {
                        ARouter.getInstance().build(ConstantArouter.PATH_APP_UPDATEACTIVITY)
                                .withString("versionInfo", JsonUtils.toJson(versionInfo))
                                .withString("fromActivity", ConstantArouter.PATH_USER_USERACTIVITY)
                                .navigation();
                    }
                }
            });
        }

        mCustomDialogUpgrade.show();

        final List<View> viewList = mCustomDialogUpgrade.getViews();
        if(null != viewList) {
            StringBuilder sb = new StringBuilder();
            sb.append(String.format("版本: %s", newVersion)).append("\n");
            sb.append(String.format("大小: %s", versionSize)).append("\n");
            sb.append("更新内容:").append("\n");
            sb.append(versionDes);
            ((AppCompatTextView) viewList.get(2)).setText(sb.toString());
        }
    }


}
